package model.behaviors;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * an abstract class implements the behavior interface and defines some of its methods
 */
public abstract class AbstractBehavior implements Behavior {

    /**
     * the image of this figure
     */
    protected BufferedImage img;

    /**
     * holds all x/y values (describing board fields) this figure can move to
     */
    ArrayList<int[]> validFields;

    /**
     * Constructor initialzing the validFields ArrayList
     */
    public AbstractBehavior()
    {
	this.validFields = new ArrayList<int[]>();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final BufferedImage getImg()
    {
	return this.img;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final ArrayList<int[]> getValidFields()
    {
	return this.validFields;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean isValidField( String pos )
    {
	boolean ret = false;
	for ( int[] fields : this.validFields )
	{
	    if ( convertXYToField( fields[0], fields[1] ).equals( pos ) )
	    {
		ret = true;
		break;
	    }
	}
	return ret;

    }

    /**
     * helping method, converts the x/y-values back to the field describing form 'A1', 'B4'..
     * 
     * @param x
     *            horizontal position
     * @param y
     *            vertical position
     * @return field name e.g. 'A2'
     */
    protected final String convertXYToField( int x, int y )
    {
	return "" + (char)( ( (char)x ) + 'A' ) + "" + ( 8 - y );
    }

    /**
     * Adds a numerical x/y combination describing a field position to the container.
     * 
     * @param x
     *            horizontal position
     * @param y
     *            vertical position
     */
    protected final void addToValidFields( int x, int y )
    {
	int[] tempField = { x, y };
	this.validFields.add( tempField );
    }

    /**
     * draws the valid fields on the board with a green rectangle
     * 
     * @param fs
     *            fieldsize as Integer
     * @param g
     *            reference to graphics object
     */
    protected final void drawFields( int fs, Graphics2D g )
    {
	// prepare..
	g.setColor( Color.GREEN );
	int strokeWidth = (int)Math.round( fs * 0.05 );
	g.setStroke( new BasicStroke( strokeWidth ) );

	System.out.println( "Groesse Array: " + this.validFields.size() );

	// draw all valid fields
	for ( int[] i : this.validFields )
	{
	    g.drawRect( fs * i[0] + strokeWidth / 2, fs * i[1] + strokeWidth / 2, fs - strokeWidth, fs - strokeWidth );
	}

	// back to default color
	g.setColor( Color.BLACK );
    }
}